package com.muzinan.template.strategy.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.muzinan.template.properties.ObjectStoreProperties;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author: MuZiNan
 * @createDate: 2022/11/25
 * @description: Oss上传策略实现类
 * @version： 1.0
 */
@Slf4j
@Getter
@Setter
@RequiredArgsConstructor
@Service("ossUploadServiceImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {

    /**
     * 构造器注入bean
     */
    private final ObjectStoreProperties properties;

    /**
     * 当前类的属性
     */
    private OSS ossClient;


    @Override
    public void initClient() {
        ossClient = new OSSClientBuilder().build(properties.getOss().getEndpoint(), properties.getOss().getAccessKey(), properties.getOss().getAccessKeySecret());
        log.info("OssClient Init Success...");
    }

    @Override
    public boolean checkFileIsExisted(String fileRelativePath) {
        return ossClient.doesObjectExist(properties.getOss().getBucket(), fileRelativePath);
    }

    @Override
    public void executeUpload(MultipartFile file, String fileRelativePath) throws IOException {
        log.info("File Upload Starts...");
        ossClient.putObject(properties.getOss().getBucket(), fileRelativePath, file.getInputStream());
        log.info("File Upload Finish...");
    }

    @Override
    public String getPublicNetworkAccessUrl(String fileRelativePath) {
        return properties.getOss().getDomainUrl() + fileRelativePath;
    }
}
